package com.aididi.config;

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @Auther: zx.xu
 * @Description:    Zuul的回退类
 * Zuul默认整合了hystrix做熔断。当请求次数失败次数过多（服务中途挂掉，试验时是5次）,
 * 将不再请求，直接返回ProviderFallback配置的内容
 */
@Component
public class GatewayZuulFallback implements FallbackProvider {

    @Override
    public String getRoute() {
        // 指定为哪个微服务提供回退
        return "service-feign";
    }


    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                //回退的状态码  ,INTERNAL_SERVER_ERROR(500, "Internal Server Error")
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                // 数字类型的状态码 500
                return this.getStatusCode().value();
            }

            @Override
            public String getStatusText() throws IOException {
                // 状态文本 Internal Server Error
                return this.getStatusCode().getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                // 响应体
                return new ByteArrayInputStream("用户微服务认证失败，请稍后再试。".getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                // 响应头
                HttpHeaders headers = new HttpHeaders();
                MediaType mt = new MediaType("application","json", StandardCharsets.UTF_8);
                headers.setContentType(mt);
                return headers;
            }
        };
    }
}
